package model

import (
	"fmt"

	"github.com/gomodule/redigo/redis"
)

// 创建全局redis连接池 句柄
var redisPool redis.Pool

// 创建函数初始化连接池
func InitRedis() {
	//连接redis ---- 连接池
	redisPool = redis.Pool{
		MaxIdle:         20,
		MaxActive:       50,
		MaxConnLifetime: 60 * 5,
		IdleTimeout:     60,
		Dial: func() (redis.Conn, error) {
			return redis.Dial("tcp", "127.0.0.1:6379")
		},
	}
}

// 校验图片验证码
func CheckImgCode(uuid, imgCOde string) bool {
	//连接redis数据库---从连接池获取连接
	//conn, err := redis.Dial("tcp", "127.0.0.1:6379")
	//if err != nil {
	//	fmt.Println("redis dial err:", err)
	//	return false
	//}
	conn := redisPool.Get()
	defer conn.Close()
	//查询redis数据
	code, err := redis.String(conn.Do("get", uuid))
	if err != nil {
		fmt.Println("redis get err:", err)
		return false
	}
	return code == imgCOde
}

// 存储短信验证码
func SaveSmsCode(phone, code string) error {
	//连接redis ---- 连接池
	conn := redisPool.Get()
	defer conn.Close()
	//存储短信验证码到redis
	_, err := conn.Do("setex", phone+"_code", 60*3, code)
	return err
}
